package com.aprivate.kn.ratingsystem.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aprivate.kn.ratingsystem.R;
import com.aprivate.kn.ratingsystem.bean.DataOfProductList;
import com.aprivate.kn.ratingsystem.bean.ProjectInfo;
import com.aprivate.kn.ratingsystem.bean.ProjectUsersBean;
import com.aprivate.kn.ratingsystem.config;
import com.aprivate.kn.ratingsystem.daoBean.Project;
import com.aprivate.kn.ratingsystem.daoutil.ProjectDaoUtil;
import com.aprivate.kn.ratingsystem.daoutil.ProjectUserDaoUtil;
import com.aprivate.kn.ratingsystem.util.GsonUtils;
import com.aprivate.kn.ratingsystem.util.StringUtilsKt;
import com.aprivate.kn.ratingsystem.view.AuditingStaffView;
import com.aprivate.kn.ratingsystem.viewUtil.ToastUtil;
import com.example.okhttputils.CallBackUtil;
import com.example.okhttputils.OkhttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class ProjectInfoActivity extends Activity {

    private DataOfProductList.ProductInfoBean mProductInfoBean;
    /**
     * 项目id
     */
    private String productInfoId;
    /**
     * 项目名
     */
    private EditText projectName;
    /**
     * 项目备注
     */
    private EditText projectDesc;
    /**
     * 单位名称
     */
    private EditText unitName;
    /**
     * 公司名称
     */
    private EditText companyName;
    /**
     * 资产范围
     */
    private EditText assetRange;
    /**
     * 审核姓名
     */
    private EditText auditingName;
    /**
     * 审核人地址
     */
    private EditText auditingAddress;
    /**
     * 审核人电话
     */
    private EditText auditingPhone;
    /**
     * 审核人邮箱
     */
    private EditText auditingEmail;
    /**
     * 审核成员list
     */
    private LinearLayout listAuditingStaff;
    /**
     * 审核成员添加
     */
    private Button addAuditingStaff;
    /**
     * 受审核单位联系人姓名
     */
    private EditText byAuditingName;
    /**
     * 受审核单位联系人地址
     */
    private EditText byAuditingAddress;
    /**
     * 受审核单位联系人电话
     */
    private EditText byAuditingPhone;
    /**
     * 受审核单位联系人邮箱
     */
    private EditText byAuditingEmail;

    /**
     * 被审核成员list
     */
    private LinearLayout listByAuditingStaff;
    /**
     * 审核成员添加
     */
    private Button addByAuditingStaff;

    /**
     * 保存信息
     */
    private Button saveInfo;
    private Context context;

    private Project mProject;
    private List<ProjectUsersBean> usersBeanList;
    private ProjectDaoUtil mProjectDaoUtil;
    private ProjectUserDaoUtil mProjectUserDaoUtil;
    private AuditingStaffView mAuditingStaffView;
    private ImageView mBack;

    public static void start(Context context, DataOfProductList.ProductInfoBean productInfoBean) {
        Intent intent = new Intent(context, ProjectInfoActivity.class);
        intent.putExtra("projectInfo", productInfoBean);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.avtivity_productioninfo);
        this.context = this;
        mBack = findViewById(R.id.img_back);
        mProductInfoBean = (DataOfProductList.ProductInfoBean) getIntent().getSerializableExtra("projectInfo");
        mProjectDaoUtil = new ProjectDaoUtil(this);
        mProjectUserDaoUtil = ProjectUserDaoUtil.getInstance();
        mProject = new Project();
        initView();
        initData();
        initListener();
    }

    private void initData() {
        productInfoId = String.valueOf(mProductInfoBean.getId());
        mProject = mProjectDaoUtil.queryProjectById(mProductInfoBean.getId());
        if (null != mProject) {
            projectName.setText(StringUtilsKt.getString(mProject.getName()));
            unitName.setText(StringUtilsKt.getString(mProject.getSecondUnit()));
            companyName.setText(StringUtilsKt.getString(mProject.getUnitName()));
            assetRange.setText(StringUtilsKt.getString(mProject.getPropertyScope()));
        } else {
            projectName.setText(StringUtilsKt.getString(mProductInfoBean.getName()));
            unitName.setText(StringUtilsKt.getString(mProductInfoBean.getSecondUnit()));
            companyName.setText(StringUtilsKt.getString(mProductInfoBean.getUnitName()));
            assetRange.setText(StringUtilsKt.getString(mProductInfoBean.getPropertyScope()));
        }
        downloadRatingInfo();
    }

    //   成员类型 1 审核组长 2审核成员 3受审单位联系人 4受访人
    private void refreshUserListView() {
        for (ProjectUsersBean usersBean : usersBeanList) {
            int type = usersBean.type;
            switch (type) {
                case 1: {
                    auditingName.setText(StringUtilsKt.getString(usersBean.name));
                    auditingAddress.setText(StringUtilsKt.getString(usersBean.addressOrPosition));
                    auditingPhone.setText(StringUtilsKt.getString(usersBean.phone));
                    auditingEmail.setText(StringUtilsKt.getString(usersBean.email));
                }
                break;
//                        case 3: {
//                            byAuditingName.setText(StringUtilsKt.getString(usersBean.name));
//                            byAuditingAddress.setText(StringUtilsKt.getString(usersBean.addressOrPosition));
//                            byAuditingPhone.setText(StringUtilsKt.getString(usersBean.phone));
//                            byAuditingEmail.setText(StringUtilsKt.getString(usersBean.email));
//                        }
//                        break;
                case 2:
                    AuditingStaffView auditingStaffView = new AuditingStaffView(this);
                    auditingStaffView.setType(2);
                    auditingStaffView.refreshStaffData(usersBean);
                    listAuditingStaff.addView(auditingStaffView);
                    break;
                case 3:
                    AuditingStaffView byAuditingStaffView = new AuditingStaffView(this);
                    byAuditingStaffView.setType(3);
                    byAuditingStaffView.refreshStaffData(usersBean);
                    listByAuditingStaff.addView(byAuditingStaffView);
                    break;
            }
        }
    }

    private void downloadRatingInfo() {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("projectId", productInfoId);
        OkhttpUtil.okHttpPost(config.URL + config.ProjectInfo_Url, paramsMap, config.getHeaderMap(), new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                refreshUserList();
            }

            @Override
            public void onResponse(String response) {
                ProjectInfo projectInfo = GsonUtils.jsonToBean(response, ProjectInfo.class);
                if (projectInfo.statusCode == 200) {
                    String dataStr = GsonUtils.toJson(projectInfo.data);
                    try {
                        JSONObject dataJObj = new JSONObject(dataStr);
                        JSONArray projectUsersJsonArray = dataJObj.getJSONArray("projectUsers");
                        ArrayList<ProjectUsersBean> projectUsersBeans = new ArrayList<>();
                        for (int i = 0; i < projectUsersJsonArray.length(); i++) {
                            JSONObject userObj = (JSONObject) projectUsersJsonArray.get(i);
                            ProjectUsersBean elements = GsonUtils.jsonToBean(userObj.toString(), ProjectUsersBean.class);
                            if (StringUtilsKt.isEmpty(elements.getName())) {
                                continue;
                            }
                            elements.projectId = Long.valueOf(productInfoId);
                            projectUsersBeans.add(elements);
                        }
                        mProjectUserDaoUtil.deleteAll();
                        mProjectUserDaoUtil.insertListProject(projectUsersBeans);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    refreshUserList();
                }
            }
        });

    }

    private void refreshUserList() {
        try {
            usersBeanList = mProjectUserDaoUtil.queryProjectByQueryBuilder(mProductInfoBean.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != usersBeanList && usersBeanList.size() > 0) {
            refreshUserListView();
        }
    }

    private void initView() {
        projectName = findViewById(R.id.et_produtionName);
        projectDesc = findViewById(R.id.et_produtionDesc);
        unitName = findViewById(R.id.et_unitName);
        companyName = findViewById(R.id.et_companyName);
        assetRange = findViewById(R.id.et_assetRange);

        auditingName = findViewById(R.id.et_auditingName);
        auditingAddress = findViewById(R.id.et_auditingAddress);
        auditingPhone = findViewById(R.id.et_auditingPhone);
        auditingEmail = findViewById(R.id.et_auditingEmail);

        listAuditingStaff = findViewById(R.id.ll_auditingStaff);
        addAuditingStaff = findViewById(R.id.bt_addAuditingStaff);
        listByAuditingStaff = findViewById(R.id.ll_byAuditingStaff);

        byAuditingName = findViewById(R.id.et_byAuditingName);
        byAuditingAddress = findViewById(R.id.et_byAuditingAddress);
        byAuditingPhone = findViewById(R.id.et_byAuditingPhone);
        byAuditingEmail = findViewById(R.id.et_byAuditingEmail);
        addByAuditingStaff = findViewById(R.id.bt_byAuditingStaffAdd);

        saveInfo = findViewById(R.id.bt_save_info);
    }

    private void initListener() {
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        addAuditingStaff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AuditingStaffView auditingStaffView = new AuditingStaffView(context);
                auditingStaffView.setTitle("审核成员");
                listAuditingStaff.addView(auditingStaffView);
            }
        });
        addByAuditingStaff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AuditingStaffView byAuditingStaffView = new AuditingStaffView(context);
                byAuditingStaffView.setTitle("受访人");
                listByAuditingStaff.addView(byAuditingStaffView);
            }
        });
        saveInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (canSave()) {
                    ProjectUserDaoUtil.getInstance().deleteAll();
                    mProjectDaoUtil.deleteProject(mProject);

                    //todo save to db
                    mProject.setId(Long.parseLong(productInfoId));
                    mProject.setName(projectName.getText().toString());
                    mProject.setRemark(projectDesc.getText().toString());
                    mProject.setUnitName(companyName.getText().toString());
                    mProject.setSecondUnit(unitName.getText().toString());
                    mProject.setPropertyScope(assetRange.getText().toString());

                    //   成员类型 1 审核组长 2审核成员 3受审单位联系人 4受访人
                    ProjectUsersBean auditingUser = new ProjectUsersBean();
                    auditingUser.setName(auditingName.getText().toString());
                    auditingUser.setAddressOrPosition(auditingAddress.getText().toString());
                    auditingUser.setPhone(auditingPhone.getText().toString());
                    auditingUser.setEmail(auditingEmail.getText().toString());
                    auditingUser.setProjectId(mProject.getId());
                    auditingUser.setType(1);

                    ProjectUsersBean byAuditingUser = new ProjectUsersBean();
                    byAuditingUser.setName(byAuditingName.getText().toString());
                    byAuditingUser.setAddressOrPosition(byAuditingAddress.getText().toString());
                    byAuditingUser.setPhone(byAuditingPhone.getText().toString());
                    byAuditingUser.setEmail(byAuditingEmail.getText().toString());
                    byAuditingUser.setProjectId(mProject.getId());
                    byAuditingUser.setType(3);

                    ProjectUserDaoUtil.getInstance().insertProject(auditingUser);
                    ProjectUserDaoUtil.getInstance().insertProject(byAuditingUser);
                    if (listAuditingStaff.getChildCount() > 0) {
                        for (int i = 0; i < listAuditingStaff.getChildCount(); i++) {
                            ProjectUsersBean interviewee = new ProjectUsersBean();
                            AuditingStaffView view = (AuditingStaffView) listAuditingStaff.getChildAt(i);
                            interviewee.setName(view.getAuditingName());
                            interviewee.setAddressOrPosition(view.getAuditingAddress());
                            interviewee.setEmail(view.getAuditingEmail());
                            interviewee.setPhone(view.getAuditingPhone());
                            interviewee.setProjectId(mProject.getId());
                            interviewee.setType(2);
                            ProjectUserDaoUtil.getInstance().insertProject(interviewee);
                        }
                    }

                    if (listByAuditingStaff.getChildCount() > 0) {
                        for (int i = 0; i < listByAuditingStaff.getChildCount(); i++) {
                            ProjectUsersBean interviewee = new ProjectUsersBean();
                            AuditingStaffView view = (AuditingStaffView) listByAuditingStaff.getChildAt(i);
                            interviewee.setName(view.getAuditingName());
                            interviewee.setAddressOrPosition(view.getAuditingAddress());
                            interviewee.setEmail(view.getAuditingEmail());
                            interviewee.setPhone(view.getAuditingPhone());
                            interviewee.setProjectId(mProject.getId());
                            interviewee.setType(3);
                            ProjectUserDaoUtil.getInstance().insertProject(interviewee);
                        }
                    }

                    if (null != mProject) {
                        mProjectDaoUtil.insertProject(mProject);
                    }
                    finish();
                }
            }
        });
    }

    private boolean canSave() {
        if (!TextUtils.isEmpty(projectName.getText())
                && !TextUtils.isEmpty(projectName.getText())
                && !TextUtils.isEmpty(unitName.getText())
                && !TextUtils.isEmpty(companyName.getText())
                && !TextUtils.isEmpty(auditingName.getText())
                && !TextUtils.isEmpty(auditingAddress.getText())
                && !TextUtils.isEmpty(auditingPhone.getText())
                && !TextUtils.isEmpty(auditingEmail.getText())) {
            return true;
        }
        ToastUtil.showShortToast(this, "请填入必填项！");
        return false;
    }
}
